{% extends 'base.html' %}

{% block head %}
<!-- Vue.js -->
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<!-- Axios -->
<script src="https://cdn.jsdelivr.net/npm/axios@1.1.2/dist/axios.min.js"></script>
<!-- 添加一些自定义样式 -->
<style>
    .modal-backdrop {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: rgba(0, 0, 0, 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 1050;
    }
    
    .modal-content {
        background-color: white;
        border-radius: 8px;
        max-width: 500px;
        width: 90%;
        padding: 20px;
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
        position: relative;
    }
    
    .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
    }
    
    .modal-footer {
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
    }
    
    .fade-enter-active, .fade-leave-active {
      transition: opacity 0.3s;
    }
    
    .fade-enter, .fade-leave-to {
      opacity: 0;
    }
</style>
{% endblock %}

{% block title %}
盲盒销售预测分析
{% endblock %}

{% block content %}
<div class="container-fluid" id="sales-prediction-app">
    <!-- 弹窗提示 -->
    {% raw %}
    <transition name="fade">
        <div class="modal-backdrop" v-if="showNoDataModal">
            <div class="modal-content">
                <div class="modal-header">
                    <h5><i class="fas fa-exclamation-circle text-warning me-2"></i>提示</h5>
                    <button type="button" class="btn-close" @click="showNoDataModal = false"></button>
                </div>
                <div class="modal-body">
                    <p>当前没有预测数据。您需要点击【运行分析】按钮生成数据。</p>
                    <p>根据您选择的分析类型和数据范围，生成结果可能需要几秒钟时间。</p>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-outline-secondary me-2" @click="showNoDataModal = false">稍后再说</button>
                    <button class="btn btn-primary" @click="runAnalysisFromModal">
                        <i class="fas fa-chart-line me-1"></i>立即分析
                    </button>
                </div>
            </div>
        </div>
    </transition>
    {% endraw %}

    <div class="row">
        <div class="col-12">
            <div class="page-title-box">
                <h4 class="page-title">
                    盲盒销售预测分析
                </h4>
            </div>
        </div>
    </div>
    
  
    <!-- 控制选项 -->
    {% raw %}
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-body">
                    <h5 class="card-title">分析设置</h5>
                    <div class="row">
                        <div class="col-md-3">
                            <div class="form-group">
                                <label>分析类型</label>
                                <select class="form-control" v-model="analysisType">
                                    <option value="forecast">销售预测</option>
                                    <option value="seasonality">季节性分析</option>
                                    <option value="elasticity">价格弹性分析</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-3" v-if="analysisType !== 'elasticity'">
                            <div class="form-group">
                                <label>商品类别</label>
                                <select class="form-control" v-model="selectedCategory">
                                    <option value="">所有类别</option>
                                    <option v-for="category in categories" :value="category">{{ category }}</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-3" v-if="analysisType === 'forecast'">
                            <div class="form-group">
                                <label>预测模型</label>
                                <select class="form-control" v-model="modelType">
                                    <option value="prophet">Prophet模型</option>
                                    <option value="arima">ARIMA模型</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-3" v-if="analysisType === 'seasonality'">
                            <div class="form-group">
                                <label>周期</label>
                                <select class="form-control" v-model="seasonalityPeriod">
                                    <option value="weekly">星期模式</option>
                                    <option value="monthly">月度模式</option>
                                </select>
                                <small class="text-muted" v-if="seasonalityPeriod === 'monthly'">
                                    月度分析建议使用至少2年数据
                                </small>
                            </div>
                        </div>
                        <div class="col-md-3" v-if="analysisType === 'elasticity'">
                            <div class="form-group">
                                <label>分析方式</label>
                                <select class="form-control" v-model="elasticityByCategory">
                                    <option :value="true">按类别分析</option>
                                    <option :value="false">整体分析</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label>数据范围</label>
                                <select class="form-control" v-model="dataDays">
                                    <option value="30">最近30天</option>
                                    <option value="90">最近3个月</option>
                                    <option value="180">最近6个月</option>
                                    <option value="365">最近1年</option>
                                    <option value="730">最近2年</option>
                                    <option value="1095">最近3年</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12 text-end">
                            <button class="btn btn-primary" @click="runAnalysis" :disabled="loading">
                                <span v-if="loading"><i class="fas fa-spinner fa-spin"></i> 分析中...</span>
                                <span v-else>运行分析</span>
                            </button> 
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 加载提示 -->
    <div class="row" v-if="loading">
        <div class="col-12">
            <div class="card">
                <div class="card-body text-center">
                    <i class="fas fa-spinner fa-spin fa-3x my-3"></i>
                    <h5>正在进行数据分析，请稍候...</h5>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 错误提示 -->
    <div class="row" v-if="error">
        <div class="col-12">
            <div class="card">
                <div class="card-body text-center text-danger">
                    <i class="fas fa-exclamation-circle fa-3x my-3"></i>
                    <h5>{{ error }}</h5>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 分析结果 -->
    <div class="row" v-if="!loading && resultData">
        <!-- 销售预测结果 -->
        <div class="col-12" v-if="analysisType === 'forecast'">
            <div class="card">
                <div class="card-body">
                    <h5 class="card-title">
                        <span v-if="resultData.box_info">{{ resultData.box_info.name }} - </span>
                        销售预测结果
                        <span v-if="resultData.box_info" class="badge bg-info ms-2">{{ resultData.box_info.category }}</span>
                    </h5>
                    <div class="row">
                        <div class="col-md-12 mb-4" v-if="resultData.charts && resultData.charts.forecast">
                            <div class="text-center">
                                <!--在time_series.py的第213行-->
                                <img :src="'data:image/png;base64,' + resultData.charts.forecast" class="img-fluid" alt="预测图表">
                            </div>
                        </div>
                        <div class="col-md-12" v-if="resultData.charts && resultData.charts.comparison">
                            <div class="text-center">
                                <img :src="'data:image/png;base64,' + resultData.charts.comparison" class="img-fluid" alt="对比图表">
                            </div>
                        </div>
                    </div>
                    <div class="row mt-4" v-if="resultData.forecast && resultData.forecast.length > 0">
                        <div class="col-md-12">
                            <h6>预测数据表</h6>
                            <div class="table-responsive">
                                <table class="table table-bordered table-hover">
                                    <thead>
                                        <tr>
                                            <th>日期</th>
                                            <th>预测销量</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr v-for="item in resultData.forecast">
                                            <td>{{ item.date }}</td>
                                            <td>{{ Math.round(item.value) }}</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 季节性分析结果 -->
        <div class="col-12" v-if="analysisType === 'seasonality'">
            <div class="card">
                <div class="card-body">
                    <h5 class="card-title">季节性分析结果</h5>
                    <div class="row">
                        <div class="col-md-12 mb-4" v-if="resultData.charts && resultData.charts.pattern">
                            <div class="text-center">
                                <img :src="'data:image/png;base64,' + resultData.charts.pattern" class="img-fluid" alt="季节性模式">
                            </div>
                        </div>
                        <div class="col-md-12" v-if="resultData.charts && resultData.charts.decomposition">
                            <div class="text-center">
                                <img :src="'data:image/png;base64,' + resultData.charts.decomposition" class="img-fluid" alt="季节性分解">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 价格弹性分析结果 -->
        <div class="col-12" v-if="analysisType === 'elasticity'">
            <div class="card">
                <div class="card-body">
                    <h5 class="card-title">价格弹性分析结果</h5>
                    <div class="row">
                        <div class="col-md-12 mb-4" v-if="resultData.charts && resultData.charts.elasticity">
                            <div class="text-center">
                                <img :src="'data:image/png;base64,' + resultData.charts.elasticity" class="img-fluid" alt="价格弹性">
                            </div>
                        </div>
                    </div>
                    <div class="row mt-4" v-if="!elasticityByCategory && resultData.elasticity !== undefined">
                        <div class="col-md-12">
                            <div class="alert" :class="{'alert-danger': Math.abs(resultData.elasticity) > 1, 'alert-warning': Math.abs(resultData.elasticity) > 0.5 && Math.abs(resultData.elasticity) <= 1, 'alert-info': Math.abs(resultData.elasticity) <= 0.5}">
                                <h5>价格弹性系数: {{ resultData.elasticity.toFixed(2) }}</h5>
                                <p>{{ resultData.interpretation }}</p>
                            </div>
                        </div>
                    </div>
                    <div class="row mt-4" v-else-if="elasticityByCategory && resultData.elasticity && resultData.elasticity.length > 0">
                        <div class="col-md-12">
                            <h6>各类别价格弹性</h6>
                            <div class="table-responsive">
                                <table class="table table-bordered table-hover">
                                    <thead>
                                        <tr>
                                            <th>类别</th>
                                            <th>价格弹性系数</th>
                                            <th>弹性类型</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr v-for="item in resultData.elasticity">
                                            <td>{{ item.category }}</td>
                                            <td>{{ item.elasticity.toFixed(2) }}</td>
                                            <td>
                                                <span class="badge" :class="{'bg-danger': Math.abs(item.elasticity) > 1, 'bg-warning': Math.abs(item.elasticity) <= 1}"
                                                      v-text="Math.abs(item.elasticity) > 1 ? '富有弹性' : '缺乏弹性'">
                                                </span>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    {% endraw %}
</div>
{% endblock %}

{% block scripts %}
<script>
    const app = new Vue({
        el: '#sales-prediction-app',
        data: {
            analysisType: 'forecast',
            selectedCategory: '',
            modelType: 'prophet',
            seasonalityPeriod: 'weekly',
            elasticityByCategory: true,
            dataDays: '365',
            loading: false,
            error: null,
            resultData: null,
            categories: ['食品', '生鲜', '烘焙', '健康', '宠物', '饮品', '日化', '美妆', '文具'],
            boxId: null,
            boxName: '',
            showNoDataModal: false
        },
        created() {
            // 组件创建时检查URL参数
            const urlParams = new URLSearchParams(window.location.search);
            
            // 如果URL中有参数，则应用这些参数
            if (urlParams.has('type')) {
                this.analysisType = urlParams.get('type');
            }
            if (urlParams.has('category')) {
                this.selectedCategory = urlParams.get('category');
            }
            if (urlParams.has('model')) {
                this.modelType = urlParams.get('model');
            }
            if (urlParams.has('period')) {
                this.seasonalityPeriod = urlParams.get('period');
            }
            if (urlParams.has('days')) {
                this.dataDays = urlParams.get('days');
            }
            if (urlParams.has('box_id')) {
                this.boxId = urlParams.get('box_id');
            }
            
            // 检查auto参数，如果为true则自动运行分析
            if (urlParams.has('auto') && urlParams.get('auto') === 'true') {
                // 使用setTimeout确保DOM已经渲染完成
                setTimeout(() => {
                    this.runAnalysis();
                }, 500);
            } else {
                // 如果不是自动运行，则显示提示弹窗
                this.checkShowModal();
            }
        },
        mounted() {
            // 在组件挂载后，如果没有数据且不是自动运行，则显示弹窗
            this.checkShowModal();
        },
        watch: {
            // 监听季节性周期变化，当选择monthly时自动调整数据范围
            seasonalityPeriod: function(newVal) {
                if (newVal === 'monthly' && this.analysisType === 'seasonality') {
                    // 如果选择月度分析，自动设置为至少2年数据
                    if (parseInt(this.dataDays) < 730) {
                        this.dataDays = '730';
                    }
                }
            },
            // 监听分析类型变化
            analysisType: function(newVal) {
                if (newVal === 'seasonality' && this.seasonalityPeriod === 'monthly') {
                    // 如果是季节性分析且选择月度，自动设置为至少2年数据
                    if (parseInt(this.dataDays) < 730) {
                        this.dataDays = '730';
                    }
                }
            }
        },
        methods: {
            checkShowModal() {
                // 如果没有结果数据，且不在加载中，显示提示弹窗
                if (!this.resultData && !this.loading) {
                    // 延迟显示弹窗，以获得更好的用户体验
                    setTimeout(() => {
                        this.showNoDataModal = true;
                    }, 800);
                }
            },
            runAnalysisFromModal() {
                // 关闭弹窗并运行分析
                this.showNoDataModal = false;
                this.runAnalysis();
            },
            runAnalysis() {
                this.loading = true;
                this.resultData = null;
                this.error = null;
                
                let apiUrl = '';
                let params = {
                    days: this.dataDays
                };
                
                // 根据分析类型构建API请求
                if (this.analysisType === 'forecast') {
                    apiUrl = '/analytics/api/sales_forecast';
                    params.model_type = this.modelType;
                    if (this.selectedCategory) {
                        params.category = this.selectedCategory;
                    }
                    if (this.boxId) {
                        params.box_id = this.boxId;
                    }
                    params.forecast_days = 30;
                } else if (this.analysisType === 'seasonality') {
                    apiUrl = '/analytics/api/seasonality_analysis';
                    params.period = this.seasonalityPeriod;
                    if (this.selectedCategory) {
                        params.category = this.selectedCategory;
                    }
                } else if (this.analysisType === 'elasticity') {
                    apiUrl = '/analytics/api/price_elasticity';
                    params.by_category = this.elasticityByCategory;
                }
                
                // 发送API请求
                axios.get(apiUrl, { params })
                    .then(response => {
                        if (response.data.success) {
                            this.resultData = response.data.data;
                        } else {
                            this.error = '分析失败: ' + response.data.message;
                        }
                        this.loading = false;
                    })
                    .catch(error => {
                        console.error('API请求失败:', error);
                        this.error = 'API请求失败: ' + (error.response ? error.response.data.message : error.message);
                        this.loading = false;
                    });
            }
        }
    });
</script>
{% endblock %}
